<template>
  <div class="article-upload-image">
    <el-upload
      class="article-image-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="uploadImageSuccess"
      name="file"
      :multiple="false"
      :headers="uploadHeader"
      :data="uploadData"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";

  export default {
    name: "UploadImage",
    model: {
      prop: 'imageUrl',
      event: 'upload-success',
    },
    props: {
      imageUrl: {
        type: String,
        default() {
          return '';
        },
      },
      type: {
        type: String,
        default() {
          return '';
        },
      },
    },
    data() {
      return {
        uploadUrl: process.env.VUE_APP_BASE_API + '/uploadImage',
        uploadHeader: {
          Authorization: 'Bearer ' + getToken(),
        },
        uploadData:{
          type: this.type
        }
      }
    },
    methods: {
      // 上传处理
      uploadImageSuccess(res, file) {
        if (res.error === 0) {
          this.$emit('upload-success', res.info.imageUrl);
        } else {
          this.$errorMessage(res.message);
        }
      },
    }
  }
</script>

<style scoped lang="less">

</style>

<style lang="less">
  @image-width: 240px;
  @image-height: 135px;
  .article-image-uploader{
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409EFF;
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: @image-width;
      height: @image-height;
      line-height: @image-height;
      text-align: center;
    }
    .avatar {
      width: @image-width;
      height: @image-height;
      display: block;
    }
  }
</style>
